package o2o.service.sync;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.company.postman.CompanyTypeRelationMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.company.postman.PostTypeMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.shop.ShopMemory;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.company.postman.PostTypeInfo;
import o2o.dao.PO.order.ORDER_GROUP_STATE;
import o2o.dao.PO.order.OrderGoods;
import o2o.dao.PO.order.OrderInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.TO.sync.*;
import o2o.service.company.postman.ShopSignCompanyService;
import org.apache.commons.lang.StringUtils;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Jahnke【1029777564@qq.com】
 * @ClassName DataSyncService
 * @Description: 数据同步
 * @date 2019/8/6 11:47
 * @Version 1.0
 */
public class DataSyncService {

    private DataSyncService() {
    }

    enum Singleton {
        INSTANCE;
        private DataSyncService single;

        private Singleton() {
            single = new DataSyncService();
        }

        private DataSyncService getInstance() {
            return single;
        }
    }

    public static DataSyncService getInstance() {
        return Singleton.INSTANCE.single;
    }

    //    @Autowired
    private ShopSignCompanyService shopSignCompanyService = ShopSignCompanyService.getInstance();

    // 商户信息同步
    public boolean syncShop(ShopTO to) {
        ShopInfo info = to.converToShop();
        List<ShopInfo> shopInfos = new ArrayList<>();
        shopInfos.add(info);
        try {
            ShopMemory.getInstance().addOrUpdate(shopInfos);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    // 商户信息同步-一次性同步多条数据
    public boolean syncShops(String json) {
        List<ShopTO> shops = JSONArray.parseArray(json, ShopTO.class);
        if (shops != null && !shops.isEmpty()) {
            List<ShopInfo> shopInfos = shops.stream().map(a -> a.converToShop()).collect(Collectors.toList());
            if (shopInfos != null && !shopInfos.isEmpty()) {
                try {
                    ShopMemory.getInstance().addOrUpdate(shopInfos);
                } catch (SQLException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }

    // 订单信息同步
    public boolean syncOrder(String orderJson) {
        OrderTO orderTO = JSONObject.parseObject(orderJson, OrderTO.class);
        if (orderTO != null) {
            OrderInfo orderInfo = orderTO.convertInfo();
            if (orderInfo == null) {
                return false;
            }
            List<OrderGoods> goods = orderTO.getGoods().stream().map(a -> a.convertInfo(orderInfo)).collect(Collectors.toList());
            try {
                OrderInfoMemory.getInstance().addOrUpdate(orderInfo, goods);
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
        return false;
    }

    // 同步云订单数据信息
    public boolean syncCloudOrder(String json) {
        CloudOrderTo_Yiyi obj = JSONObject.parseObject(json, CloudOrderTo_Yiyi.class);
        String masterOrderNo = StringUtils.isNotEmpty(obj.getOrderNo()) ? obj.getOrderNo() : obj.getId().toString();
        obj.setOrderNo(masterOrderNo);
        OrderInfo masterOrder = obj.convertInfo();
        masterOrder.setGroupState(ORDER_GROUP_STATE.GROUP_STATE_PARENT);
        List<CloudOrderShopTO_Yiyi> shops = obj.getShop();
        if (shops == null || shops.isEmpty()) {
            return false;
        }
        Map<OrderInfo, List<OrderGoods>> ogs = new HashMap<>();
        for (int i = 0; i < shops.size(); i++) {
            OrderInfo zOrder = shops.get(i).convertInfo(masterOrder);
            // 获取对应的购买产品
            List<OrderGoods> goods = shops.get(i).getGoods().stream().map(a -> a.convertInfo(zOrder)).collect(Collectors.toList());
            ogs.put(zOrder, goods);
        }
        try {
            OrderInfoMemory.getInstance().addOrUpdateOrders(masterOrder, ogs);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    // 商户签约数据同步
    public boolean syncShopSignInfo(String signJson) {
        List<ShopSignDeliverComTO> list = JSONArray.parseArray(signJson, ShopSignDeliverComTO.class);
        if (list != null) {
            try {
                shopSignCompanyService.addOrUpdate(list);
                return true;
            } catch (SQLException e) {
                return false;
            }
        }
        return false;
    }

    // 获取订单状态
    public List<OrderStatusTO> listOrderStatus(Set<String> set) {
        List<OrderInfo> orderInfoList = new ArrayList<>();
        for (String orderNo : set) {
            OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (info != null) {
                orderInfoList.add(info);
            }
        }
        if (orderInfoList != null && !orderInfoList.isEmpty()) {
            return orderInfoList.stream().map(a -> {
                return new OrderStatusTO()
                        .setOrderNo(a.getOrderNo()).setOrderStatus(a.getOrderStatus());
            }).collect(Collectors.toList());
        }
        return null;
    }

    // 获取配送公司信息
    public List<PostCompanyTO> listPostCompanyTO(String city) {
        List<PostCompanyInfo> list = null;
        if (!StringUtils.isEmpty(city)) {
            list = PostCompanyMemory.getInstance().listOfCity(city, null);
        } else {
            list = PostCompanyMemory.getInstance().listAll();
        }
        if (ValidateUtil.isAbsList(list)) {
            List<PostCompanyTO> postCompanyTOList = list.stream().map(a -> a.convert2TO()).collect(Collectors.toList());
            return postCompanyTOList.stream().map(a -> {
                Set<Long> set = CompanyTypeRelationMemory.getInstance().listOfByCompanyId(a.getId());
                if (set != null && !set.isEmpty()) {
                    List<PostTypeInfo> typeInfos = set.stream().map(id -> PostTypeMemory.getInstance().getById(id)).filter(bean -> bean != null).collect(Collectors.toList());
                    if (typeInfos != null && !typeInfos.isEmpty()) {
                        a.setPostTypeList(typeInfos.stream().map(model -> model.convert2TO()).collect(Collectors.toList()));
                    }
                }
                return a;
            }).collect(Collectors.toList());
        }
        return null;
    }

    public static void main(String[] args) {
        String str = "{\"id\":1,\"orderNo\":\"A001\",\"shop\":[{\"shopId\":1,\"shopName\":\"店铺1\",\"goods\":[{\"goodsId\":1,\"name\":\"商品1\"}]}]}";
        CloudOrderTo_Yiyi obj = JSONObject.parseObject(str, CloudOrderTo_Yiyi.class);
        System.out.println(JSON.toJSON(obj));
    }
}
